package com.blb.ssm.utils;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtils {
	
	static SqlSessionFactory sqlSessionFactory=null;
	static SqlSession session=null;
	
	public static <T>T getMapper(Class<T> type){
		try {
			if(sqlSessionFactory ==null){
				String resource = "mybatis-config.xml";
				InputStream inputStream=Resources.getResourceAsStream(resource);;
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			}
			session = sqlSessionFactory.openSession();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return session.getMapper(type);
	}
	
	/**
	 * 提交
	 */
	public static void commit(){
		session.commit();
	}
	
	/**
	 * 关闭session
	 */
	public static void closeSession(){
		session.close();
	}
}
